package com.wkk.quartz.utils;

import com.wkk.exception.NoBugException;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.stereotype.Component;

/**
   *
   * @author : WangKeKe
   * @date : 2020/8/17 18:19
   * Description : Quartz工具类
   *
 */

@Component
@Slf4j
public class QuartzUtil {

    /**
     * 添加定时任务
     * - 将Job和Trigger放入Scheduler中调度
     * @param jobClassName  Job模板路径
     * @param cronExpression Cron表达式
     * @param parameter 参数
     * @param scheduler 任务调度
     */
    public  void schedulerAdd(String jobClassName, String cronExpression, String parameter,Scheduler scheduler) {
        try {
            // 启动调度器
            scheduler.start();

            // 构建job信息
            JobDetail jobDetail = JobBuilder.newJob(getClass(jobClassName).getClass()).withIdentity(jobClassName).usingJobData("parameter", parameter).build();

            // 表达式调度构建器(即任务执行的时间)
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);

            // 按新的cronExpression表达式构建一个新的trigger
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(jobClassName).withSchedule(scheduleBuilder).build();

            scheduler.scheduleJob(jobDetail, trigger);
        } catch (SchedulerException e) {
            throw new NoBugException("创建定时任务失败", e);
        } catch (RuntimeException e) {
            throw new NoBugException(e.getMessage(), e);
        }catch (Exception e) {
            throw new NoBugException("后台找不到该类名：" + jobClassName, e);
        }
    }


    /**
     * 通过反射获取对象
     * @param classname 类路径
     * @return job 任务对象
     * @throws Exception 异常处理
     */
    public Job getClass(String classname) throws Exception {
        Class<?> class1 = Class.forName(classname);
        return (Job) class1.newInstance();
    }

    /**
     * 删除定时任务
     * - 将Job和Trigger从Scheduler中移除
     * @param jobClassName 任务类名
     * @param scheduler 任务调度对象
     */
    public void schedulerDelete(String jobClassName, Scheduler scheduler) {
        try {
            scheduler.pauseTrigger(TriggerKey.triggerKey(jobClassName));
            scheduler.unscheduleJob(TriggerKey.triggerKey(jobClassName));
            scheduler.deleteJob(JobKey.jobKey(jobClassName));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new NoBugException("删除定时任务失败");
        }
    }
}
